﻿using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;

namespace RayD.Core
{
    /// <summary>
    /// 登录信息处理类
    /// </summary>
    public static class AuthenticationHelper
    {
        /// <summary>
        /// 获取ClaimsPrincipal
        /// </summary>
        private static ClaimsPrincipal claimsPrincipal
        {
            get
            {
                //认证
                return HttpContextHelper.Instance?.AuthenticateAsync()?.Result?.Principal;
            }
        }

        /// <summary>
        /// 保存登录状态 for Cookie
        /// </summary>
        /// <param name="claims"></param>
        public static void Save(params Claim[] claims)
        {
            //创建一个身份证
            ClaimsIdentity claimsIdentity = new ClaimsIdentity("Cookie");
            //往身份证写入用户信息
            claimsIdentity.AddClaims(claims);
            //登录
            HttpContextHelper.Instance.SignInAsync(new ClaimsPrincipal(claimsIdentity));
        }
        /// <summary>
        /// 清除登录状态
        /// </summary>
        public static void Clear()
        {
            //退出
            HttpContextHelper.Instance.SignOutAsync();
        }
        /// <summary>
        /// 获取Claims中的值
        /// </summary>
        /// <param name="ClaimTypes">Claims的键</param>
        /// <returns></returns>
        public static string Get(string ClaimTypes)
        {
            //授权
            return claimsPrincipal?.FindFirstValue(ClaimTypes);
        }
        /// <summary>
        /// 用户是否登录 false：未登录/登录失效 true：已登录
        /// </summary>
        /// <returns></returns>
        public static bool IsOnline()
        {
            //认证
            if (claimsPrincipal == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 获取登录用户信息
        /// </summary>
        public static UserInfo LoginUserInfo
        {
            get
            {
                //授权
                return Get(ClaimTypes.UserData).ToObject<UserInfo>() ?? new UserInfo();

            }
        }
    }
}
